import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'

Vue.use(VueAxios, axios)

const instance = axios.create({
  baseURL: 'http://toutiao.itheima.net',
  timeout: 10000
})

import { getToken, saveToken } from './token.js'

//导入toast弹窗
import { Toast } from 'vant'
//导入路由router (这个文件导入的router就是vue原型中的$router)
import router from '@/router/index.js'

instance.interceptors.request.use(
  function (config) {
    if (getToken()) {
      config.headers.Authorization = `Bearer ${getToken().token}`
    }
    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)

instance.interceptors.response.use(
  function (response) {
    return response
  },
  async function (error) {
    if (error.response && error.response.status == 401) {
      if (getToken()) {
        try {
          let res = await axios({
            url: 'http://toutiao.itheima.net/v1_0/authorizations',
            method: 'put',
            headers: {
              Authorization: `Bearer ${getToken().refresh_token}`
            }
          })
          console.log(res)
          saveToken({
            token: res.data.data.token,
            refresh_token: getToken().refresh_token
          })
          return instance(error.config)
        } catch (err) {
          Toast.success('请先登录')
          router.push('/login')
        }
      } else {
        Toast.success('请先登录')
        router.push('/login')
      }
    } else {
    }
    return Promise.reject(error)
  }
)

export default instance
